# -*- coding: utf-8 -*-
import math
import pickle
from abc import ABC

from app.views import CommonHandler
from app.models.dao import db_session, db2vectors, delete
from app.models.model import PositionModel
from app.models.model import TrackModel


class PositionHandler(CommonHandler, ABC):
    async def get(self):
        meta_id = self.get_argument("meta_id", None)
        dxftype = self.get_argument("type", None)

        session = db_session()
        features = session.query(PositionModel).filter(
            PositionModel.meta_id == meta_id,
            PositionModel.dxftype == dxftype
        ).all()
        session.close()

        positions = [feature.vector() for feature in features]
        await self.respose(data=positions)

    async def post(self):
        params, session = self.json_params(), db_session()
        insert_id = str(params['track_id']) if 'track_id' in params else None

        # 判断一下当前类型下,是否存在分站id相同的情况
        positions = db_session().query(PositionModel).filter(
            PositionModel.node_id == params["node_id"],
            PositionModel.meta_id == params['meta_id'],
            PositionModel.dxftype == params["type"]
        )

        # 添加或修改分站信息
        if positions.count() > 0:
            # 如果分站记录已经存在,则更新分站记录
            for p in positions:
                position = session.query(PositionModel).filter_by(id=p.id).first()
                position.point = pickle.dumps(params['point'])
                position.insert_id = insert_id
                session.commit()
        else:
            # 如果查询不到数据,则创建一条分站记录
            position = PositionModel(params['point'], params['meta_id'])
            position.node_id = params["node_id"]
            position.dxftype = params["type"]
            position.insert_id = insert_id
            session.add(position)

        # 更新轨迹线数据
        if 'track_id' in params and 'track' in params:
            tracks = session.query(TrackModel).filter(TrackModel.id == params['track_id']).all()
            for track in tracks:
                track.points = pickle.dumps(params['track'])

        session.commit()
        session.close()

        data = {
            'positions': db2vectors(PositionModel, params['meta_id']),
            'tracks': db2vectors(TrackModel, params['meta_id'])
        }

        await self.respose(data=data)

    async def put(self):
        params, session = self.json_params(), db_session()

        # 增加一个新的定位卡
        positions = session.query(PositionModel).filter(PositionModel.id == params['node_id']).all()
        x, y = params['point'][0], params['point'][1]
        for position in positions:
            position.point = pickle.dumps(params['point'])
            position.x, position.y = x, y
            position.left, position.right = math.floor(x), math.ceil(x)
            position.top, position.bottom = math.ceil(y), math.floor(y)

        # 更新轨迹线数据
        tracks = session.query(TrackModel).filter(TrackModel.id == params['track_id']).all()
        for track in tracks:
            track.points = pickle.dumps(params['track'])
        session.commit()
        session.close()

        data = {
            'positions': db2vectors(PositionModel, params['meta_id']),
            'tracks': db2vectors(TrackModel, params['meta_id'])
        }
        await self.respose(data=data)

    async def delete(self):
        params = self.json_params()
        delete(PositionModel, params['id'])
        positions = db2vectors(PositionModel, params['meta_id'])
        await self.respose(data=positions)
